package com.photoeditor.demo.ui.activity.edit;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.av.edit.VideoFilterDevice;
import com.android.av.play.AspectFrameLayout;
import com.android.av.play.MoviePlayer;
import com.android.av.play.SpeedControlCallback;
import com.android.gpuimage.GPUImage;
import com.android.gpuimage.GPUImageFilter;
import com.android.gpuimage.GPUImageFilterGroup;
import com.android.gpuimage.GPUImageNormalBlendFilter;
import com.android.gpuimage.GPUImageOESFilter;
import com.android.gpuimage.IRenderCallback;
import com.android.gpuimage.Rotation;
import com.android.gpuimage.util.LocationUtil;
import com.android.videolib.VideoCooker;
import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.common.commercialize.utils.TaskRunnable;
import com.photoeditor.R;
import com.photoeditor.demo.app.ActionConstant;
import com.photoeditor.demo.db.FilterCategoryBean;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.UseEffectInfo;
import com.photoeditor.demo.model.event.RefreshFilterCategory;
import com.photoeditor.demo.model.event.SortFilterCategory;
import com.photoeditor.demo.model.filter.ImageFilterTools;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.community.ConfirmUploadActivity;
import com.photoeditor.demo.ui.dialog.RateGuide;
import com.photoeditor.demo.ui.fragement.HomeFragment;
import com.photoeditor.demo.ui.widget.BottomInsideBarView;
import com.photoeditor.demo.ui.widget.CustomNumSeekBar;
import com.photoeditor.demo.ui.widget.DashedImageView;
import com.photoeditor.demo.ui.widget.LoadingView;
import com.photoeditor.demo.ui.widget.OnSeekBarChangeListener;
import com.photoeditor.demo.ui.widget.image.FilterBarView;
import com.photoeditor.demo.ui.widget.image.watermark.Watermark;
import com.photoeditor.demo.ui.widget.image.watermark.WatermarkLinearLayout;
import com.photoeditor.demo.ui.widget.image.watermark.WatermarkManager;
import com.photoeditor.demo.ui.widget.image.watermark.WatermarkSelectView;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.DialogUtils;
import com.photoeditor.demo.util.FontUtil;
import com.photoeditor.demo.util.ImageRectUtils;
import com.photoeditor.demo.util.MediaTypeUtil;
import com.photoeditor.demo.util.folder.FolderHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.photoeditor.demo.statistics.StatisticsConstant.SOURCE_TYPE_EDIT;
import static com.photoeditor.demo.util.DataConstant.MAX_DURATION_VIDEO;

public class EditorVideoActivity extends MediaEditBaseActivity implements View.OnClickListener {

    public static final String EXTRA_NAME_FILE_PATH = "extra_file_path";
    private static final String TAG = EditorVideoActivity.class.getName();
    private static final String EXTRA_FROM_GIF = "EXTRA_FROM_GIF";
    private static final String EXTRA_WATERMARK = "EXTRA_WATERMARK";
    private static final String EXTRA_ORIGINAL_FILE_PATH = "EXTRA_ORIGINAL_FILE_PATH";
    private static final String EXTRA_ORIGINAL_FILE_MEDIA_TYPE = "EXTRA_ORIGINAL_FILE_MEDIA_TYPE";
    //可以显示评分引导的子包特效
    private static final String EXTRA_CAN_SHOW_RATE_APK_EFFECT_PACKAGE_NAME = "EXTRA_CAN_SHOW_RATE_APK_EFFECT_PACKAGE_NAME";
    //特效类型
    private static final String EXTRA_CAN_SHOW_RATE_APK_EFFECT_TYPE = "EXTRA_CAN_SHOW_RATE_APK_EFFECT_TYPE";
    private static final String EXTRA_CAN_SHOW_RATE_APK_EFFECT_NAME = "EXTRA_CAN_SHOW_RATE_APK_EFFECT_NAME";

    private AspectFrameLayout mAspectFrameLayout;
    private GLSurfaceView mSurfaceView;
    private GPUImage mGpuImage;
    private FilterBarView mFilterView;
    private View mBottomTab;
    private BottomInsideBarView mBottomLayoutInSide;
    private TextView mProgressTv;
    private View mProgressLayout;

    private String mPath;
    private int mDegrees;
    private int mBitRate;
    private int mWidth;
    private int mHeight;
    private long mDuration;
    private String[] mLocation;

    private MoviePlayer.PlayTask mPlayTask;

    private Object mRequestStartLock = new Object();
    private boolean mRequestStart;

    private boolean mIsNeedPublish;

    private ProgressDialog mSaveTaskProgressDialog;

    private ViewGroup mFilterOperationViewContainer;
    //水印相关
    private WatermarkManager mWatermarkManager;
    private boolean mWaterMarkIsExist;
    private View mWaterMarkBottomTab;
    // 用于添加水印filter
    private ViewGroup mWaterMarkLayer;
    private RelativeLayout mWaterMarkLayout;
    private ImageView mWaterMarkIV;
    private View mWaterMarkBarLayout;

    private Animation mBottomLayoutBottomOut;
    private Animation mBottomLayoutTopIn;
    private Animation mBottomLayoutBottomIn;
    private Animation mBottomLayoutTopOut;

    private boolean mIsFromGif = false;

    private String mOriginalFilePath;
    private int mOriginalFileMediaType;
    private UseEffectInfo mUseEffectInfo;


    private AsyncTask mGetBitmapTask;
    private ArrayList<String> mTmpVideos;

    private boolean mOnSaveOperation; // 是否由保存操作而关闭页面

    private VideoFilterDevice.ResultCallback mResultCallback = new VideoFilterDevice.ResultCallback() {
        @Override
        public void onError() {
            StatisticsUtils.statisticsMakeVideoResult(EditorVideoActivity.class.getSimpleName(), false, mWidth, mHeight);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideProgressDialog();
                    handleError(R.string.video_edit_save_failed);
                }
            });
        }

        @Override
        public void onSuccess(File outputFile) {
            StatisticsUtils.statisticsMakeVideoResult(EditorVideoActivity.class.getSimpleName(), true, mWidth, mHeight);
            deleteGifFile();
            outputFile = FolderHelper.checkMoveToExtSdcard(EditorVideoActivity.this, outputFile, "video/mp4");
            FolderHelper.broadcastVideoFile(ComponentContext.getContext(), outputFile, null,
                    new FolderHelper.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(final String path, final Uri uri, int orientation) {


                            ThreadPool.runUITask(new Runnable() {
                                @Override
                                public void run() {
                                    TaskRunnable runnable = new TaskRunnable(2000, TaskRunnable.TYPE_MAIN) {
                                        @Override
                                        public void run() {
                                            hideProgressDialog();
                                            SPDataManager.setEditCount(SPDataManager.getEditCount() + 1);
                                            statisticsSave();
                                            finishActivity(uri);
                                            if (mIsNeedPublish) {
                                                ConfirmUploadActivity.startConfirmUploadActivity(EditorVideoActivity.this, path, getTopicIdFromIntent());
                                            }
                                        }
                                    };
                                    onSave(runnable);
                                }
                            });

                        }
                    });
        }
    };
    private String mMainButtonEntrance;
    private boolean mFilterUsed;
    private boolean hasShowWatermarkSVip = false;

    private void deleteGifFile() {
        if (mIsFromGif && new File(mPath).exists()) {
            new File(mPath).delete();
        }
    }

    private LoadingView mLoadingView;

    public void clickedButton(View view) {
        if (mFilterView != null) {
//            mFilterView.clickedButton(view);
        }
    }

    public static void startVideoEditActivity(Activity context, String filePath, String action, int requestCode) {
        Intent intent = new Intent(context, EditorVideoActivity.class);
        intent.setAction(action);
        intent.putExtra(EXTRA_NAME_FILE_PATH, filePath);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startVideoEditActivity(Activity context, String filePath, String action, int requestCode, String mainButtonEntrance) {
        Intent intent = new Intent(context, EditorVideoActivity.class);
        intent.setAction(action);
        intent.putExtra(EXTRA_NAME_FILE_PATH, filePath);
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startVideoEditActivity(Activity context, String filePath, int requestCode, int topicId) {
        Intent intent = new Intent(context, EditorVideoActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_MOTION_EDIT_AND_PUBLISH);
        intent.putExtra(EXTRA_NAME_FILE_PATH, filePath);
        intent.putExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, topicId);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startVideoEditActivity(Activity context, String filePath, int requestCode) {
        Intent intent = new Intent(context, EditorVideoActivity.class);
        intent.putExtra(EXTRA_NAME_FILE_PATH, filePath);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startVideoEditActivityFromGif(Activity context, String filePath, Watermark watermark, String originalFilePath, int originaFileType, UseEffectInfo useEffectInfo) {
        Intent intent = new Intent(context, EditorVideoActivity.class);
        intent.putExtra(EXTRA_NAME_FILE_PATH, filePath);
        intent.putExtra(EXTRA_FROM_GIF, "fromGif");
        intent.putExtra(EXTRA_WATERMARK, watermark);
        intent.putExtra(EXTRA_ORIGINAL_FILE_PATH, originalFilePath);
        intent.putExtra(EXTRA_ORIGINAL_FILE_MEDIA_TYPE, originaFileType);
        if (useEffectInfo != null) {
            intent.putExtra(RateGuide.INTENT_RATE_EFFECT_INFO, useEffectInfo);
        }

        intent.setAction(ActionConstant.Actions.ACTION_PICK_TO_EDIT);
        context.startActivityForResult(intent, GalleryActivity.REQUEST_CODE_PICK_TO_EDIT);

    }

    public static void startVideoEditActivity(Context context, String filePath, int topicId) {
        Intent intent = new Intent(context, EditorVideoActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_MOTION_EDIT_AND_PUBLISH);
        intent.putExtra(EXTRA_NAME_FILE_PATH, filePath);
        intent.putExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, topicId);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private void finishActivity(Uri uri) {
        Toast.makeText(EditorVideoActivity.this, getResources().getString(R.string.image_edit_save_success), Toast.LENGTH_SHORT).show();
        Intent i = new Intent();
        i.setData(uri);
        Bundle bundle = checkAndGetRateBundle(uri == null ? null : uri.toString());
        if (bundle != null) {
            i.putExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE, bundle);
        }
        setResult(RESULT_OK, i);

        if (ActionConstant.Actions.ACTION_PICK_TO_EDIT.equals(getIntent().getAction())) {

//            PictureViewActivity.startPictureViewActivity(VideoEditActivity.this, mIsPrivate);
            ImagePreviewActivity.startPictureViewActivityAndStartShare(EditorVideoActivity.this, uri, bundle, mMainButtonEntrance);
        }

        mOriginalFilePath = null;
        mOriginalFileMediaType = MediaTypeUtil.TYPE_OTHER_IMAGE;
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageLoader.clearMemoryCache();
        setContentView(R.layout.activity_video_editor);
        mWatermarkManager = new WatermarkManager(this);
        mWatermarkManager.setWatermarkUpdateListener(new WatermarkManager.OnWatermarkUpdateListener() {
            @Override
            public void onWatermarkUpdate() {
                refreshWaterMark();
                mWaterMarkIV.setImageBitmap(mWatermarkManager.getWatermarkBitmap(mWatermarkManager.getCurrentWatermark()));
            }
        });
        Intent intent = getIntent();
        mPath = intent.getStringExtra(EXTRA_NAME_FILE_PATH);
        mIsFromGif = "fromGif".equals(intent.getStringExtra(EXTRA_FROM_GIF));
        if (TextUtils.isEmpty(mPath)) {
            handleError(R.string.video_edit_open_failed);
            return;
        }

        mUseEffectInfo = intent.getParcelableExtra(RateGuide.INTENT_RATE_EFFECT_INFO);
        if (mUseEffectInfo == null) {
            mUseEffectInfo = new UseEffectInfo();
        }

        mOriginalFilePath = intent.getStringExtra(EXTRA_ORIGINAL_FILE_PATH);
        if (mOriginalFilePath == null) {
            mOriginalFilePath = mPath;
        }
        mOriginalFileMediaType = intent.getIntExtra(EXTRA_ORIGINAL_FILE_MEDIA_TYPE, mIsFromGif ? MediaTypeUtil.TYPE_GIF : MediaTypeUtil.TYPE_VIDEO);

        mIsNeedPublish = ActionConstant.Actions.ACTION_MOTION_EDIT_AND_PUBLISH.equals(intent.getAction());

        mMainButtonEntrance = intent.getStringExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE);

        mGetBitmapTask = new AsyncTask<Object, Void, Boolean>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showProgressDialog();
            }

            @Override
            protected Boolean doInBackground(Object... params) {
                try {
                    initMetadata();
                } catch (Exception e) {
                }
                if (mDuration > MAX_DURATION_VIDEO) {
                    // 视频大于30s，需要裁剪为30s后使用
                    clipBeyond30sVideo();
                }
                return mDuration > 0;
            }

            @Override
            protected void onPostExecute(Boolean o) {
                super.onPostExecute(o);
                hideProgressDialog();
                if (o) {
                    doInit();
                } else {
                    handleError(R.string.video_edit_open_failed);
                    finish();
                }
            }
        };
        mGetBitmapTask.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR);
    }

    private void doInit() {
        initViews();
        double aspectRatio = mWidth / (double) mHeight;
        if (mDegrees == 90 || mDegrees == 270) {
            aspectRatio = mHeight / (double) mWidth;
        }
        mAspectFrameLayout.setAspectRatio(aspectRatio);
        mAspectFrameLayout.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mFilterView != null) {
                    mFilterView.dealOnTouch(v, event);
                }
                return true;
            }
        });

        initGPUImage();

        initBottomLayoutInSide();
        showInsideBottomBarWithName(getCurrentFilterName());
        EventBus.getDefault().register(this);

//        if (!AppVipManager.isVip() && !mIsFromGif) {
//            mAdProvider = new EditCompleteAdProvider(this);
//            mAdProvider.loadAd();
//
//            EditCompleteAdProvider.statistics("in", "where", "video");
//        } else {
//            if (AppVipManager.isVip()) {
//                AdProvider.statisticsNoRequestAd(EditCompleteAdProvider.SCENE_NAME, AdProvider.REASON_SVIP_USER);
//            }
//        }
    }

    private void initViews() {
        mFilterOperationViewContainer = (ViewGroup) findViewById(R.id.edit_operation_view);
        mFilterOperationViewContainer.setVisibility(View.VISIBLE);

        mAspectFrameLayout = (AspectFrameLayout) findViewById(R.id.aspect_frameLayout);
        mAspectFrameLayout.setVisibility(View.VISIBLE);
        mSurfaceView = (GLSurfaceView) findViewById(R.id.play_surfaceView);

        mFilterView = (FilterBarView) findViewById(R.id.filter_bar);
        mFilterView.hidevignetteTiltshiftButton();
        mFilterView.setSourceType(SOURCE_TYPE_EDIT);
        mBottomTab = findViewById(R.id.bottom_tab);
        mBottomLayoutInSide = (BottomInsideBarView) findViewById(R.id.bottom_layout_inside);
        mBottomLayoutInSide.setVisibility(View.VISIBLE);
        mProgressTv = (TextView) findViewById(R.id.progress_tv);
        mProgressLayout = findViewById(R.id.progress_layout);

        initResource();
        mWaterMarkIsExist = mWatermarkManager.isWatermarkExist();

        mWaterMarkBottomTab = findViewById(R.id.bottom_tab_water);
        FontUtil.setCustomFontBold((TextView) mWaterMarkBottomTab.findViewById(R.id.type_text_water));
        mWaterMarkBottomTab.findViewById(R.id.cancel_water).setOnClickListener(this);
        mWaterMarkBottomTab.findViewById(R.id.confirm_water).setOnClickListener(this);

        initWaterMark();

        mBottomLayoutInSide.setConfirmEnable(mIsFromGif || mWaterMarkIsExist);
    }

    private void initMetadata() {
        MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
        retrieverSrc.setDataSource(mPath);
        String degreesString = retrieverSrc.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
        if (degreesString != null) {
            mDegrees = Integer.valueOf(degreesString);
        }
        String bitrateString = retrieverSrc.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_BITRATE);
        if (bitrateString != null) {
            mBitRate = Integer.valueOf(bitrateString);
        }
        String widthString = retrieverSrc.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
        mWidth = Integer.valueOf(widthString);
        String heightString = retrieverSrc.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
        mHeight = Integer.valueOf(heightString);
        String durationString = retrieverSrc.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_DURATION);
        mDuration = Long.valueOf(durationString);
        String locationString = retrieverSrc.extractMetadata(
                MediaMetadataRetriever.METADATA_KEY_LOCATION);
        mLocation = LocationUtil.parseLocation(locationString);
        retrieverSrc.release();
    }

    private void initGPUImage() {
        mGpuImage = new GPUImage(this, true);
        mGpuImage.setFilter(new GPUImageOESFilter(), true);
        mGpuImage.setGLSurfaceView(mSurfaceView);
        mGpuImage.setRotation(Rotation.fromInt(mDegrees));
        mGpuImage.setRenderCallback(new IRenderCallback() {
            @Override
            public void onSurfaceTextureCreated(SurfaceTexture surfaceTexture) {
                MoviePlayer mPlayer = null;
                try {
                    mPlayer = new MoviePlayer(new File(mPath), new Surface(surfaceTexture),
                            new SpeedControlCallback());
                } catch (IOException e) {
                    handleError(R.string.video_edit_open_failed);
                    return;
                }

                synchronized (mRequestStartLock) {
                    mPlayTask = new MoviePlayer.PlayTask(mPlayer, null);
                    mPlayTask.setLoopMode(true);
                    if (mRequestStart) {
                        mPlayTask.requestStart();
                    }
                    mWaterMarkLayout.setOnClickListener(EditorVideoActivity.this);
                    setWaterMarkVisible(true);
                }
            }

            @Override
            public void onFrameAvaliable(long frameTimeNanos) {

            }
        });
    }

    private void initBottomLayoutInSide() {
        mBottomLayoutInSide.setOnProgressChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(CustomNumSeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(CustomNumSeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(CustomNumSeekBar seekBar, int progress,
                                          boolean fromUser) {
                mProgressTv.setText(progress + "");
                if (fromUser) {
                    mFilterView.onProgressChange(progress);
                }
            }
        });
        mBottomLayoutInSide.setOnClickListener(this);
    }

    public String getCurrentFilterName() {
        if (mFilterView != null) {
            return mFilterView.getCurrentFilterName();
        } else {
            return ImageFilterTools.FILTER_NAME_DEFAULT;
        }
    }

    private int getTopicIdFromIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            return intent.getIntExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, 0);
        }
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == StoreConstant.EDIT_REQUESTCODE) {//编辑了Filter
//            if (mFilterView != null) {
//                mFilterView.onActivityResult(requestCode, resultCode, data);
//            }
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSortFilterCategory(final SortFilterCategory event) {
        if (mFilterView != null) {
            mFilterView.onSortFilterCategory(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, priority = 1)
    public void onRefreshFilterCategory(final RefreshFilterCategory event) {
        if (TextUtils.isEmpty(event.delCategoryId) && !TextUtils.isEmpty(event.showCategoryId)) {
            // 在这里应用滤镜后，取消后面的接收者接收事件
            EventBus.getDefault().cancelEventDelivery(event);
        }
        if (mFilterView != null) {
            mFilterView.onRefreshFilterCategory(event);
        }
    }


    public void initResource() {
        int primaryColor = getResources().getColor(R.color.windowBackgroundColor);
        int emphasisColor = getResources().getColor(R.color.accent_color);
        mProgressLayout.setBackgroundResource(R.drawable.image_edit_sencond_bg);
        mProgressTv.setBackgroundResource(R.drawable.bg_image_edit_big_progress);
        mProgressTv.setTextColor(getResources().getColor(R.color.image_edit_big_progress_text_color));

        if (mProgressTv != null) {
            setDefaultProgressTvBgColor(emphasisColor);
        }
    }

    @Override
    public void showBottomBar(boolean outSide, int type) {
        mBottomLayoutInSide.setType(type);
    }

    /**
     * 底部变成mBottomLayoutInSide 中间显示名称
     *
     * @param name
     */
    public void showInsideBottomBarWithName(String name) {
        mBottomLayoutInSide.setNameText(name);
        showBottomBar(false, BottomInsideBarView.TYPE_NAME);
    }

    /**
     * 底部变成mBottomLayoutInSide 中间进度条
     * 这个用于滤镜  滤镜的进度条根据传入的颜色来确认
     *
     * @param progress
     * @param color
     */
    public void showInsideBottomBarWithProgress(int progress, int color) {
//        mBottomLayoutInSide.setSeekBarColor(color);
//        setProgressTvBgColor(color);
        mBottomLayoutInSide.setProgress(progress);
        showBottomBar(false, BottomInsideBarView.TYPE_PROGRESS);
    }

    @Override
    public int getSeekBarProgress() {
        return mBottomLayoutInSide.getProgress();
    }

    @Override
    public void setFilter(GPUImageFilter filter) {
        boolean isDefaultFilter = filter == null || filter.getClass() == GPUImageFilter.class;
        GPUImageFilterGroup group = new GPUImageFilterGroup();
        group.addFilter(new GPUImageOESFilter());
        group.addFilter(filter);
        mGpuImage.setFilter(group, true);

        mBottomLayoutInSide.setConfirmEnable(mIsFromGif || mWaterMarkIsExist || !isDefaultFilter);
        mFilterUsed = true;
    }

    @Override
    public void clearFilter(GPUImageFilter filter) {

    }

    @Override
    public void requestRender() {
        mGpuImage.requestRender();
    }

    @Override
    public void setConfirmEnable(boolean flag) {

    }

    private void setProgressTvBgColor(int color) {
        Drawable d = mProgressTv.getBackground();
        d.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        mProgressTv.setBackgroundDrawable(d);
    }

    private void setDefaultProgressTvBgColor(int defalutColor) {
        Drawable d = mProgressTv.getBackground();
        d.clearColorFilter();
        d.setColorFilter(defalutColor, PorterDuff.Mode.SRC_IN);
        mProgressTv.setBackgroundDrawable(d);
    }

    @Override
    protected void onStart() {
        super.onStart();
        startPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
        if (mFilterView != null) {
            mFilterView.onDestory();
        }
//        if (mAdProvider != null) {
//            mAdProvider.destroyAd();
//        }
        try {
            if (mGetBitmapTask != null) {
                mGetBitmapTask.cancel(true);
            }
        } catch (Exception e) {
        }
        delTmpVideo();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.cancel) {
            deleteGifFile();
            onExit();
        } else if (id == R.id.confirm) {
            confirm();
        } else if (id == R.id.watermark_layout) {
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_WATERMARK_CLICK);
            showOperationsViewByTabId(R.id.watermark);
            if (!mWatermarkManager.isWatermarkExist()) {
                mWaterMarkIV.setImageBitmap(null);
            }
            refreshWaterMark();
            startBottomBarAppearAnimation(true);
        } else if (id == R.id.cancel_water || id == R.id.confirm_water) {
            if (id == R.id.confirm_water) {
                mWatermarkManager.saveLastUseWatermark();
            }
            showOperationsViewByTabId(R.id.filter);
            mBottomLayoutInSide.setConfirmEnable(mIsFromGif || mWaterMarkIsExist);
            startBottomBarAppearAnimation(false);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        deleteGifFile();
        onExit();
    }

    public void startBottomBarAppearAnimation(boolean outSide) {
        if (outSide) {
            mWaterMarkBottomTab.setVisibility(View.VISIBLE);
            mBottomLayoutInSide.setVisibility(View.GONE);
            mWaterMarkBottomTab.startAnimation(getBottomIn());
            mBottomLayoutInSide.startAnimation(getTopOut());
        } else if (!outSide && mBottomLayoutInSide.getVisibility() == View.GONE) {
            mBottomLayoutInSide.setVisibility(View.VISIBLE);
            mWaterMarkBottomTab.setVisibility(View.GONE);
            mWaterMarkBottomTab.startAnimation(getBottomOut());
            mBottomLayoutInSide.startAnimation(getTopIn());
        }
    }

    public Animation getBottomIn() {
        if (mBottomLayoutBottomIn == null) {
            mBottomLayoutBottomIn = AnimationUtils.loadAnimation(this, R.anim.bottom_in);
        } else {
            mBottomLayoutBottomIn.reset();
        }
        return mBottomLayoutBottomIn;
    }

    public Animation getBottomOut() {
        if (mBottomLayoutBottomOut == null) {
            mBottomLayoutBottomOut = AnimationUtils.loadAnimation(this, R.anim.bottom_out);
        } else {
            mBottomLayoutBottomOut.reset();
        }
        return mBottomLayoutBottomOut;
    }

    public Animation getTopIn() {
        if (mBottomLayoutTopIn == null) {
            mBottomLayoutTopIn = AnimationUtils.loadAnimation(this, R.anim.top_in);
        } else {
            mBottomLayoutTopIn.reset();
        }
        return mBottomLayoutTopIn;
    }

    public Animation getTopOut() {
        if (mBottomLayoutTopOut == null) {
            mBottomLayoutTopOut = AnimationUtils.loadAnimation(this, R.anim.top_out);
        } else {
            mBottomLayoutTopOut.reset();
        }
        return mBottomLayoutTopOut;
    }

    /**
     * 显示对应tabid的操作视图
     *
     * @param tab_id
     */
    private void showOperationsViewByTabId(int tab_id) {

        int childcount = mFilterOperationViewContainer.getChildCount();
        for (int index = 0; index < childcount; index++) {
            View childView = mFilterOperationViewContainer.getChildAt(index);
            childView.setVisibility(View.GONE);
        }

        if (tab_id == R.id.filter) {
            if (mFilterView != null) {
                mFilterView.reset();
            }
            mFilterView.setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.watermark) {
            getWatermarkBarView().setVisibility(View.VISIBLE);
        }
    }

    private void startPlay() {
        synchronized (mRequestStartLock) {
            if (mPlayTask != null) {
                mRequestStart = false;
                mPlayTask.requestStart();
            } else {
                mRequestStart = true;
            }
        }
    }

    private void stopPlay() {
        synchronized (mRequestStartLock) {
            mRequestStart = false;
            if (mPlayTask != null) {
                mPlayTask.requestStop();
            }
        }
    }

    private Bundle checkAndGetRateBundle(String outputPath) {
        if (mUseEffectInfo == null) {
            return null;
        }
        if (mFilterView != null) {
            FilterCategoryBean currentFilterCategoryBean = mFilterView.getCurrentFilterCategoryBean();
            if (currentFilterCategoryBean != null) {
                mUseEffectInfo.add(currentFilterCategoryBean);
            }
        }
//        return RateGuide.newBundle(mOriginalFilePath,
//                mOriginalFileMediaType,
//                outputPath,
//                mIsFromGif ? MediaTypeUtil.TYPE_GIF : MediaTypeUtil.TYPE_VIDEO,
//                mUseEffectInfo);
        return null;
    }

    private void confirm() {
        final String filterName = getCurrentFilterName();
        if (ImageFilterTools.FILTER_NAME_DEFAULT.equals(filterName) && !mWaterMarkIsExist && !mIsFromGif) {
            TaskRunnable runnable = new TaskRunnable(TaskRunnable.TYPE_POSTING) {
                @Override
                public void run() {
                    statisticsSave();
                    if (mIsNeedPublish) {
                        ConfirmUploadActivity.startConfirmUploadActivity(EditorVideoActivity.this, mPath, getTopicIdFromIntent());
                    }
                    finish();
                }
            };
            onSave(runnable);
            return;
        }
        Watermark watermark = mWatermarkManager.getCurrentWatermark();
        if (mWaterMarkIsExist && watermark != null) {
            StatisticsUtils.statisticsCustomPreviewClick(watermark.getStatisticName());
        }
        stopPlay();

        showProgressDialog();
        ((DashedImageView) mWaterMarkIV).setShowBoundEnable(false);
        postDelayed(new Runnable() {
            @Override
            public void run() {
                GPUImageFilterGroup group = new GPUImageFilterGroup();
                group.addFilter(new GPUImageOESFilter());
                if (!ImageFilterTools.FILTER_NAME_DEFAULT.equals(filterName)) {
                    group.addFilter(mFilterView.newCurrentFilter());
                }
                // 添加水印filter
                if (mWaterMarkIsExist) {
                    GPUImageNormalBlendFilter waterMarkFilter = new GPUImageNormalBlendFilter();
                    Bitmap cache = mWaterMarkLayer.getDrawingCache();
                    if (cache != null) {
                        waterMarkFilter.setBitmap(cache);
                        group.addFilter(waterMarkFilter);
                    }
                }
                final File file = FolderHelper.getOutputMediaFile(EditorVideoActivity.this, FolderHelper.MEDIA_TYPE_DYNAMIC, false);
                try {
                    VideoFilterDevice device = new VideoFilterDevice(new File(mPath), file, group,
                            mWidth, mHeight, mDegrees, mBitRate, mLocation, mResultCallback);
                    device.start();
                } catch (Exception e) {
                    hideProgressDialog();
                    handleError(R.string.video_edit_save_failed);
                }
            }
        }, 100);
    }

    private void handleError(final int resId) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                try {
                    Toast.makeText(ComponentContext.getContext(), resId, Toast.LENGTH_SHORT).show();
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showProgressDialog() {
        if (mSaveTaskProgressDialog == null) {
            mSaveTaskProgressDialog = DialogUtils.showCoverProgressDialog(this);
        } else {
            mSaveTaskProgressDialog.show();
        }
        if (mLoadingView == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.loading_stub);
            mLoadingView = (LoadingView) stub.inflate();
        }
        mLoadingView.startLoading();
    }

    private void hideProgressDialog() {
        if (mLoadingView != null) {
            mLoadingView.stopLoading();
        }
        if (mSaveTaskProgressDialog != null && !isFinishing()) {
            mSaveTaskProgressDialog.dismiss();
        }
    }

    /**
     * 下面是水印相关
     */
    private void initWaterMark() {
        mWaterMarkLayer = (ViewGroup) findViewById(R.id.watermark_layer);
        mWaterMarkLayer.setVisibility(View.VISIBLE);
        mWaterMarkLayer.setDrawingCacheEnabled(true);
        mWaterMarkLayout = (RelativeLayout) findViewById(R.id.watermark_layout);
        mWaterMarkIV = (ImageView) findViewById(R.id.watermark);
        Watermark watermark = (Watermark) getIntent().getSerializableExtra(EXTRA_WATERMARK);
        if (watermark == null) {
            watermark = mWatermarkManager.getCurrentWatermark();
        }
        if (mWatermarkManager.isPlaceholderWatermark(watermark)) {//没有水印
            mWaterMarkIV.setImageBitmap(null);
        } else {
            Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
            if (bitmap != null) {
                mWaterMarkIV.setImageBitmap(bitmap);
            }
        }
        mAspectFrameLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {

            @Override
            public void onLayoutChange(View v, int left, int top, int right,
                                       int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                refreshWaterMark();
            }
        });

//	    mWaterMarkLayout.setOnClickListener(this);
    }

    /**
     * 刷新水印
     */
    private void refreshWaterMark() {
        mAspectFrameLayout.post(new Runnable() {

            @Override
            public void run() {
                if (mPlayTask != null && mWaterMarkLayout != null && mWaterMarkLayout.getVisibility() == View.VISIBLE) {
                    //水印View的父View是mImageView的父View
                    setWaterMarkPosition(ImageRectUtils.getViewRect(mAspectFrameLayout), ImageRectUtils.getViewRect(mAspectFrameLayout));
                }
            }
        });
    }


    /**
     * viewRect是父View的Rect
     *
     * @param viewRect
     * @param drawRect
     */
    private void setWaterMarkPosition(RectF viewRect, RectF drawRect) {
        Watermark watermark = mWatermarkManager.getCurrentWatermark();

        RectF waterMarkRect = BitmapUtils.getWaterMarkRect(this, drawRect, watermark);

        int padding = DeviceUtils.dip2px(this, 5);

        float left = waterMarkRect.left - padding;
        if (left < drawRect.left) {
            left = drawRect.left;
        }
        float top = waterMarkRect.top - padding;
        if (top < drawRect.top) {
            top = drawRect.top;
        }
        float right = waterMarkRect.right + padding;
        if (right > drawRect.right) {
            right = drawRect.right;
        }
        float bottom = waterMarkRect.bottom + padding;
        if (bottom > drawRect.bottom) {
            bottom = drawRect.bottom;
        }
        RectF waterMarkLayoutRect = new RectF(left, top, right, bottom);

        FrameLayout.LayoutParams layoutLp = (FrameLayout.LayoutParams) mWaterMarkLayout.getLayoutParams();
        int width = (int) (waterMarkLayoutRect.width() + 0.5f);
        int height = (int) (waterMarkLayoutRect.height() + 0.5f);
        int topMargin = (int) (waterMarkLayoutRect.top - viewRect.top);
        int leftMargin = (int) (waterMarkLayoutRect.left - viewRect.left);
        if (width != layoutLp.width || height != layoutLp.height || topMargin != layoutLp.topMargin || leftMargin != layoutLp.leftMargin) {
            layoutLp.width = width;
            layoutLp.height = height;
            layoutLp.topMargin = topMargin;
            layoutLp.leftMargin = leftMargin;
            mWaterMarkLayout.setLayoutParams(layoutLp);
        }

        RelativeLayout.LayoutParams ivLp = (RelativeLayout.LayoutParams) mWaterMarkIV.getLayoutParams();
        width = (int) waterMarkRect.width();
        height = (int) waterMarkRect.height();
        leftMargin = (int) (waterMarkRect.left - left);
        topMargin = (int) (waterMarkRect.top - top);
        if (width != ivLp.width || height != ivLp.height || topMargin != ivLp.topMargin || leftMargin != ivLp.leftMargin) {
            ivLp.width = width;
            ivLp.height = height;
            ivLp.topMargin = topMargin;
            ivLp.leftMargin = leftMargin;
            mWaterMarkIV.setLayoutParams(ivLp);
        }
    }

    /**
     * 水印可见或者不可见
     *
     * @param visible
     */
    private void setWaterMarkVisible(final boolean visible) {
        mAspectFrameLayout.post(new Runnable() {
            @Override
            public void run() {
                if (visible) {
                    mWaterMarkLayout.setVisibility(View.VISIBLE);
                } else {
                    mWaterMarkLayout.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * watermark的选择View
     *
     * @return
     */
    private View getWatermarkBarView() {
        if (mWaterMarkBarLayout == null) {
            initWatermarkbarView();
        }
        return mWaterMarkBarLayout;
    }

    private void initWatermarkbarView() {
        ViewStub stub = (ViewStub) findViewById(R.id.watermark_bar_stub);
        mWaterMarkBarLayout = stub.inflate();
        LinearLayout view = (LinearLayout) mWaterMarkBarLayout.findViewById(R.id.watermark_bar_layout);
        initWatermarkBar(view);
    }

    private void initWatermarkBar(LinearLayout view) {
        List<Watermark> watermarkList = mWatermarkManager.getAvailableWatermarks();
        mWaterMarkBarLayout.setBackgroundResource(R.drawable.image_edit_sencond_bg);
        int size = watermarkList.size();
        int width = getResources().getDimensionPixelSize(R.dimen.watermark_width);
        View.OnClickListener onclick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Watermark watermark = (Watermark) v.getTag();
                if (watermark == null) {
                    return;
                }
                mWatermarkManager.setCurrentWatermark(watermark);
                if (mWatermarkManager.isPlaceholderWatermark(watermark)) {
//                    if(!hasShowWatermarkSVip && !AppVipManager.isVip()) {
//                        hasShowWatermarkSVip = true;
//                        SVipController.getInstance().showPurchaseActivityOfWatermark();
//                    }
                    mWaterMarkIsExist = false;
                    mWaterMarkIV.setImageBitmap(null);
                } else {
                    mWaterMarkIsExist = true;
                    Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
                    if (bitmap != null) {
                        mWaterMarkIV.setImageBitmap(bitmap);
                    }
                }
                refreshWaterMark();
            }
        };
        for (int i = 0; i < size; i++) {
            WatermarkSelectView demoView = new WatermarkSelectView(this);
            demoView.setTag(watermarkList.get(i));
            demoView.setBackgroundResource(R.drawable.image_edit_sencond_bg_selector);
            demoView.setOnClickListener(onclick);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, WindowManager.LayoutParams.MATCH_PARENT);
            demoView.setImageResource(watermarkList.get(i).getDemoResId());
            demoView.setWatermarkInfo(mWatermarkManager, watermarkList.get(i));
            view.addView(demoView, lp);
            if (watermarkList.get(i) == mWatermarkManager.getCurrentWatermark()
                    && view instanceof WatermarkLinearLayout) {
                ((WatermarkLinearLayout) view).setSelectView(demoView);
            }
        }
    }

    @Override
    public boolean isSupport(int type) {
        switch (type) {
            case BaseOnlineManager.STORE_FUNC_TYPE_FILTER:
                return true;
        }
        return false;
    }

    @Override
    public void finish() {
        super.finish();
//        if(!mOnSaveOperation && mAdProvider != null) {
//            mAdProvider.onExit(null);
//        }
    }

    private void delTmpVideo() {
        if (mTmpVideos != null && mTmpVideos.size() > 0) {
            for (String tmp : mTmpVideos) {
                com.common.base.utils.FileUtil.delete(new File(tmp));
            }
        }
    }

    // 耗时操作
    private void clipBeyond30sVideo() {
        verifyMediaPath();
        String tmpDir = com.common.base.utils.FileUtil.getExternalCacheDir(ComponentContext.getContext(), "cltmp");
        String tmpFile = tmpDir + File.separator + System.currentTimeMillis() + ".mp4";
        if (mTmpVideos == null) {
            mTmpVideos = new ArrayList<>();
        }
        mTmpVideos.add(tmpFile);
        VideoCooker.clipVideo(mPath, tmpFile, 0, MAX_DURATION_VIDEO / 1000);
        // 裁剪后输出文件不存在，使用原视频编辑
        if (new File(tmpFile).exists()) {
            mPath = tmpFile;
        }
        try {
            initMetadata();
        } catch (Exception e) {
        }
    }

    private void onExit() {
        /*if(mAdProvider != null) {
            TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                @Override
                public void run() {
                    finish();
                }
            };
            mAdProvider.onExit(taskRunnable, "video");
        } else {
            finish();
        }*/
//        EditCompleteAdProvider.statistics("exit", "where", "video");
        statisticsMainBtnEditBack();
        finish();
    }

    private void onSave(TaskRunnable taskRunnable) {
//        if(mAdProvider != null) {
//            mOnSaveOperation = true;
//            mAdProvider.onSave(taskRunnable, "video");
//        } else {
        if (taskRunnable != null) {
            taskRunnable.runSelfAdaptation();
        }
//        }
    }

    /**
     * ffmpeg不支持文件路径中有空格，需要把有空格的文件先拷贝到临时目录
     */
    private void verifyMediaPath() {
        String path = mPath;
        if (!TextUtils.isEmpty(path) && path.contains(" ")) {
            String tmpDir = com.common.base.utils.FileUtil.getExternalCacheDir(ComponentContext.getContext(), "cltmp");
            String tmpFile = tmpDir + File.separator + System.currentTimeMillis() + ".mp4";
            try {
                com.common.base.utils.FileUtil.copyFile(path, tmpFile, true);
            } catch (Exception e) {
                return;
            }
            if (mTmpVideos == null) {
                mTmpVideos = new ArrayList<>();
            }
            mTmpVideos.add(tmpFile);
            mPath = tmpFile;
        }
    }

    public void statisticsMainBtnEditBack() {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
            StatisticsUtils.statisticsMainBtnEditCancel(mMainButtonEntrance);
        }
    }

    public void statisticsSave() {
        if (TextUtils.isEmpty(mMainButtonEntrance)) {
            return;
        }
        statisticsMainBtnEditSave("save");
        if (mFilterUsed) {
            statisticsMainBtnEditSave("filter");
        }
        if (mWaterMarkIsExist) {
            statisticsMainBtnEditSave("watermark");
        }
    }

    public void statisticsMainBtnEditSave(String useWhat) {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
            StatisticsUtils.statisticsMainBtnEditSave(mMainButtonEntrance, useWhat);
        }
    }
}
